import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout/home' // 默认显示layout和layout下的home
  },
  {
    path: '/login',
    // 路由懒加载的形式
    component: () => import('@/views/Login')
  },
  {
    path: '/layout',
    component: () => import('@/views/Layout'),
    children: [
      {
        path: 'home',
        component: () => import('@/views/Home'),
        meta: {
          scrollT: 0 // 保存首页离开时,滚动条位置
        }
      },
      {
        path: 'user',
        component: () => import('@/views/User')
      }
    ]
  },
  {
    path: '/search',
    component: () => import('@/views/Search')
  },
  // 搜索结果页
  {
    path: '/search_result/:kw',
    component: () => import('@/views/Search/SearchResult')
  },
  // 文章详情页
  {
    path: '/detail',
    component: () => import('@/views/ArticleDetail')
  },
  {
    // 用户编辑页面
    path: '/user_edit',
    component: () => import('@/views/User/UserEdit')
  },
  // 聊天页面
  {
    path: '/chat',
    component: () => import('@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})

// 路由 - 全局前置守卫(在路由发生真正跳转之前,执行次函数)
// 此函数可以决定路由是否跳转/取消/强制中断切换到别的路由
router.beforeEach((to, from, next) => {
  // 如果已经登陆了,不要切换到登录页面
  if (getToken()?.length > 0 && to.path === '/login') {
    next('/layout/home') // 返回到首页
  } else {
    next() // 其他情况都放行
  }
})

export default router
